import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login } from '../api/auth'

// 定义用户角色类型
export type UserRole = 'ADMIN' | 'TEACHER' | 'STUDENT' | ''

// 定义用户数据接口
export interface UserData {
  token: string
  userId: string | null
  username: string
  roleType: UserRole
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(localStorage.getItem('token') || '')
  const userId = ref<string | null>(localStorage.getItem('userId') || null)
  const username = ref<string>(localStorage.getItem('username') || '')
  const roleType = ref<UserRole>(localStorage.getItem('roleType') as UserRole || '')

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)

  // 登录
  function setUser(data: UserData): void {
    token.value = data.token
    userId.value = data.userId
    username.value = data.username
    roleType.value = data.roleType
    
    // 保存到localStorage
    localStorage.setItem('token', data.token)
    localStorage.setItem('userId', data.userId || '')
    localStorage.setItem('username', data.username)
    localStorage.setItem('roleType', data.roleType)
  }

  // 登出
  function logout(): void {
    token.value = ''
    userId.value = null
    username.value = ''
    roleType.value = ''
    
    // 清除localStorage
    localStorage.removeItem('token')
    localStorage.removeItem('userId')
    localStorage.removeItem('username')
    localStorage.removeItem('roleType')
  }

  // 检查是否为管理员（兼容大小写）
  const isAdmin = computed(() => {
    const role = roleType.value?.toUpperCase()
    return role === 'ADMIN'
  })
  
  // 检查是否为教师（兼容大小写）
  const isTeacher = computed(() => {
    const role = roleType.value?.toUpperCase()
    return role === 'TEACHER'
  })
  
  // 检查是否为学生（兼容大小写）
  const isStudent = computed(() => {
    const role = roleType.value?.toUpperCase()
    return role === 'STUDENT'
  })

  return {
    token,
    userId,
    username,
    roleType,
    isLoggedIn,
    isAdmin,
    isTeacher,
    isStudent,
    setUser,
    logout
  }
})

